package com.sunday.electric.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.sunday.common.event.EventBus;
import com.sunday.common.utils.Constants;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.electric.R;
import com.sunday.electric.base.BaseFragment;
import com.sunday.electric.event.LoginOut;
import com.sunday.electric.ui.LoginActivity;
import com.sunday.electric.ui.MainActivity;
import com.sunday.electric.ui.ShowBigImage;
import com.sunday.electric.ui.XWalkExUiClient;
import com.sunday.electric.ui.mine.DetailViewActivity;
import com.sunday.electric.ui.mine.OnLineHelpActivity;
import com.sunday.electric.ui.mine.WebViewActivity;
import com.sunday.electric.utils.SharePerferenceUtils;

import org.xwalk.core.JavascriptInterface;
import org.xwalk.core.XWalkCookieManager;
import org.xwalk.core.XWalkPreferences;
import org.xwalk.core.XWalkResourceClient;
import org.xwalk.core.XWalkSettings;
import org.xwalk.core.XWalkView;
import org.xwalk.core.XWalkWebResourceRequest;
import org.xwalk.core.XWalkWebResourceResponse;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2016/1/9.
 */
public class IndexFragment extends BaseFragment {
    @Bind(R.id.webView)
    XWalkView mXWalkView;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;
    private String localUrl = "file:///android_asset/test.html";
    private String baseHostPort = "202.110.130.19:1080";
    private String aliYunHostPort = "120.27.149.184:1080";
    private String companyHostPort = "10.136.192.179:3080";

    private String indexUrl = "http://"+baseHostPort+"/RedAS/app/appPage.go?method=goHomePage&t=";
    private String plainUrl = "http://"+baseHostPort+"/RedAS/app/appPage.go?method=goPlanListPage&t=";
    private String thirdUrl = "http://"+baseHostPort+"/RedAS/app/appPage.go?method=goJcPlanListPage&t=";
    private String addPlainUrl = "http://"+baseHostPort+"/RedAS/app/appPage.go?method=goPlanAddPage";

    private XWalkCookieManager mCookieManager;

    public static boolean decoderBase64File(String base64Code, String savePath) {
        if (base64Code == null) // 图像数据为空
            return false;
        try {
            // Base64解码
            byte[] bytes = Base64.decode(base64Code, Base64.DEFAULT);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(savePath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_index, null);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mCookieManager = new XWalkCookieManager();
        mCookieManager.setAcceptCookie(true);
        mCookieManager.setAcceptFileSchemeCookies(true);
        mXWalkView.load(indexUrl + new Date().getTime(), null);
        mXWalkView.clearCache(false);
        emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
        mXWalkView.setUIClient(new XWalkExUiClient(mXWalkView));
//        XWalkPreferences.setValue(XWalkPreferences.REMOTE_DEBUGGING, true);
        //   mXWalkView.load("javascript:document.body.contentEditable=true;", null);
        mXWalkView.addJavascriptInterface(new JsInterface(), "NativeInterface");
        mXWalkView.setResourceClient(new XWalkResourceClient(mXWalkView) {

            @Override
            public void onReceivedLoadError(XWalkView view, int errorCode, String description, String failingUrl) {
                emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
                super.onReceivedLoadError(view, errorCode, description, failingUrl);
            }

            @Override
            public void onLoadFinished(XWalkView view, String url) {
                emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                super.onLoadFinished(view, url);
            }

            @Override
            public XWalkWebResourceResponse shouldInterceptLoadRequest(XWalkView view, XWalkWebResourceRequest request) {
                return super.shouldInterceptLoadRequest(view, request);
            }

            @Override
            public void onLoadStarted(XWalkView view, String url) {
                super.onLoadStarted(view, url);
            }
        });
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mXWalkView.load(indexUrl + new Date().getTime(), null);
            }
        });
    }

    public void loadIndex() {
        mXWalkView.getNavigationHistory().clear();
        mXWalkView.load(indexUrl + new Date().getTime(), null);
    }

    public void loadPlain() {
        mXWalkView.getNavigationHistory().clear();
        mXWalkView.load(plainUrl + new Date().getTime(), null);
    }

    public void loadThird() {
        mXWalkView.getNavigationHistory().clear();
        mXWalkView.load(thirdUrl + new Date().getTime(), null);
    }

    public void loadAddPlain() {
        mXWalkView.load(addPlainUrl, null);
    }

    public void clearCache() {
        mXWalkView.getNavigationHistory().clear();
    }

    public XWalkView getmXWalkView() {
        return mXWalkView;
    }

    public Bitmap stringtoBitmap(String string) {
        //将字符串转换成Bitmap类型
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bitmap;
    }


    public class JsInterface {
        public JsInterface() {
        }

        //获取登录用户名
        @JavascriptInterface
        public String getUserName() {
            return SharePerferenceUtils.getIns().getOAuth().getLoginName();
        }

        //获取登录密码
        @JavascriptInterface
        public String getUserPwd() {
            return SharePerferenceUtils.getIns().getOAuth().getPassword();
        }

        //打开侧边栏接口
        @JavascriptInterface
        public void openMenu() {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ((MainActivity) getActivity()).openMenu();
                }
            });

        }

        //签到接口 参数为计划id
        @JavascriptInterface
        public void sign(String planId) {
            ((MainActivity) getActivity()).sign(planId);
        }

        //到岗到位领导签到接口 参数计划Id
        @JavascriptInterface
        public void signLeader(String planId) {
            ((MainActivity) getActivity()).signLeader(planId);
        }

        //首页调用计划
        @JavascriptInterface
        public void clickPlan() {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ((MainActivity) getActivity()).onTabClick(1);
                }
            });
        }

        //返回键
        @JavascriptInterface
        public void doReturn() {
            ((WebViewActivity) getActivity()).finish();
        }


        //首页调用检查
        @JavascriptInterface
        public void clickCheck() {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ((MainActivity) getActivity()).onTabClick(2);
                }
            });
        }

        //首页调用二维码界面
        @JavascriptInterface
        public void clickQrcode() {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ((MainActivity) getActivity()).openQrcode();
                }
            });

        }

        //首页调用聊天界面
        @JavascriptInterface
        public void clickOnLineHelp() {
            intent = new Intent(mContext, OnLineHelpActivity.class);
            startActivity(intent);
        }

        //与相应人员聊天
        @JavascriptInterface
        public void clickChatPerson(String loginName) {
            intent = new Intent(mContext, OnLineHelpActivity.class);
            intent.putExtra("loginName", loginName);
            startActivity(intent);
        }

        //从列表打开的详情采用新webviewActivity方式
        @JavascriptInterface
        public void openDetail(String url) {
            intent = new Intent(mContext, DetailViewActivity.class);
            intent.putExtra("url", url);
            startActivity(intent);
        }

        //app重新登录
        @JavascriptInterface
        public void appLogin() {
            EventBus.getDefault().post(new LoginOut());
            SharePerferenceUtils.getIns().removeKey(Constants.IS_LOGIN);
            intent = new Intent(mContext, LoginActivity.class);
            startActivity(intent);
        }


        //产看图片接口
        @JavascriptInterface
        public void showImage(String path) {
            if (TextUtils.isEmpty(path)) {
                return;
            }
      /*      byte[]bitmapArray;
            bitmapArray=Base64.decode(path, Base64.DEFAULT);*/
            //     String tempPath = writeImageToDisk(bitmapArray);
            // String tempPath = ImageUtils.saveBitmap(stringtoBitmap(path));
            // String tempPath  = StringUtils.getRandomString(32)+".jpg";
            // File file = new File("/sdcard",tempPath);
            // decoderBase64File(path,file.getPath());
            String tempPath = path;
            intent = new Intent(mContext, ShowBigImage.class);
            intent.putExtra("imgPath", tempPath);
            startActivity(intent);
        }
    }
}
